package com.atlin.controller;


import cn.hutool.json.JSONUtil;
import com.atlin.license.LicenseVerify;
import com.atlin.model.LicenseContentVo;
import com.atlin.model.ServerInfoModel;
import com.atlin.service.LicenseService;
import com.atlin.util.SM4Encryptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * license管理
 */
@RestController
@RequestMapping("/license")
@RequiredArgsConstructor
public class LicenseCreatorController {

    private final LicenseService licenseService;

    /**
     * 获取服务器硬件信息
     */
    @GetMapping(value = "/getServerInfos")
    public ServerInfoModel getServerInfos() {
        return licenseService.getServerInfos();
    }


    /**
     * 获取机器码信息文件
     */
    @GetMapping(value = "/getServerInfosFile")
    public void getServerInfosFile(HttpServletResponse response) {
        ServerInfoModel serverInfos = licenseService.getServerInfos();

        try {
            // 1. 将对象转换为格式化后的 JSON 字符串
            String context = SM4Encryptor.encryptCBC(JSONUtil.toJsonStr(serverInfos));
            // 2. 文件名（可包含时间）
            String fileName = URLEncoder.encode(
                    "server-info-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".dta",
                    StandardCharsets.UTF_8
            );

            // 3. 设置响应头，告诉浏览器下载文件
            response.setContentType("application/json;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            // 4. 写入文件内容
            try (OutputStream os = response.getOutputStream()) {
                os.write(context.getBytes(StandardCharsets.UTF_8));
                os.flush();
            }

        } catch (Exception e) {
            throw new RuntimeException("导出服务器信息失败", e);
        }
    }

    /**
     * 导入License
     *
     * @param file License 文件
     */
    @PostMapping(value = "/importLicense", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public LicenseContentVo importLicense(@RequestParam("file") MultipartFile file) {
        return licenseService.importLicense(file);
    }

    /**
     * 获取License详情
     */
    @GetMapping("/getLicenseInfo")
    public LicenseContentVo getLicenseInfo() {
        return licenseService.getLicenseInfo();
    }

    /**
     * 验证测试
     */
    @GetMapping("/test")
    public String test(HttpServletRequest request) {
        LicenseVerify licenseVerify = new LicenseVerify();
        licenseVerify.verify(request);
        return "ok";
    }


}
